<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>AJAX 登录示例</title>
</head>
<body>
<form id="loginForm">
    <input type="text" id="username" placeholder="输入用户名">
    <input type="password" id="password" placeholder="输入密码">
    <button type="submit">登录</button>
</form>
<p id="msg" style="color: red;"></p>

<script>
    document.getElementById("loginForm").addEventListener("submit", async function(event) {
        event.preventDefault(); // 阻止表单默认提交行为

        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value.trim();
        const msg = document.getElementById("msg");

        if (!username || !password) {
            msg.innerText = "请输入用户名和密码！";
            return;
        }

        try {
            const response = await fetch("login", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`,
                credentials: "include"
            });

            const data = await response.json();

            if (data.success) {
                alert("登录成功！");
                window.location.href = "welcome.html"; // 登录成功跳转
            } else {
                msg.innerText = data.message;
            }
        } catch (error) {
            console.error("请求失败:", error);
            msg.innerText = "服务器连接失败！";
        }
    });
</script>
</body>
</html>
